<?php

if (!defined('CORE_PATH'))
    die('Access Denied');

// EventManager class definition
class EventsManager extends Manager {

    protected $models = array('Event', 'EventCategory');
    protected $template = "events.php";

    function __construct() {
        parent::__construct('events', 'event_categories');
        $this->setItemClassName('Events');
        $this->setCategoryClassName('EventCategory');
    }
    
    public function addEvent() {
        if( !defined("IN_CMS") || !IN_CMS ) {
            return;
        }
        
        $event = new Event(array(
            'EventCategory' => $_POST['EventCategory'],
            'EventName' => $_POST['EventName'],
            'EventDesc' => $_POST['EventDesc'],
            'Time' => $_POST['Time'],
            'EventDuration' => $_POST['EventDuration'],
            'Date' => $_POST['EventDuration'] == "single" ? $_POST['Date'] : $_POST['StartDate'],
            'StartDate' => $_POST['EventDuration'] == "single" ? $_POST['Date'] : $_POST['StartDate'],
            'EndDate' => $_POST['EndDate'],
            'Venue' => $_POST['Venue'],
            'FriendlyURL' => $_POST['FriendlyURL']
        ));
        
        $event->save();
    }
    
    public function updateEvent() {
        if( !defined("IN_CMS") || !IN_CMS ) {
            return;
        }
        
        $event = new Event(array(
            'EventCategory' => $_POST['EventCategory'],
            'EventName' => $_POST['EventName'],
            'EventDesc' => $_POST['EventDesc'],
            'Time' => $_POST['Time'],
            'EventDuration' => $_POST['EventDuration'],
            'Date' => $_POST['EventDuration'] == "single" ? $_POST['Date'] : $_POST['StartDate'],
            'StartDate' => $_POST['EventDuration'] == "single" ? $_POST['Date'] : $_POST['StartDate'],
            'EndDate' => $_POST['EndDate'],
            'Venue' => $_POST['Venue'],
            'FriendlyURL' => $_POST['FriendlyURL'],
            'id' => $_POST['id']
        ));
        
        $event->save();
    }

    /**
     * Returns an array containing the database records of the event categories
     * of the specified site. If not SiteID is specified, all event categories
     * in the system will be loaded
     *
     * @param int $siteid the database record ID of the site to load info for
     * @return array an array of database records
     */
    public function getEventCategories($options = NULL) {
        $default = array(
            'filter' => array(
                'SiteID' => SITE_ID
            )
        );
        
        if( is_array($options) ) {
            $default = array_merge($default, $options);
        }
        
        return $this->EventCategory->find( $default );
    }

    public function getEventCategory($category_id) {
        
        return $this->EventCategory->findFirst(array(
            'filter' => array(
                'SiteID' => SITE_ID,
                'OR' => array(
                    'id' => $category_id,
                    'CategoryAlias' => $category_id
                )
            )
        ));
    }

    /**
     * Returns a list of events from the database
     * @return array the events 
     */
    public function getEvents($start = 0, $limit = NULL, $publishedOnly = true, $excludePast = true) {
        $db = $this->getDatabase();
        $pub = $publishedOnly ? " AND Published = 'true' " : "";
        $past = $excludePast ? " AND (StartDate >= CURRENT_DATE OR EndDate >= CURRENT_DATE) " : "";

        $query = sprintf("SELECT Event.* FROM {$this->Event->getTableName()} AS Event
							INNER JOIN {$this->EventCategory->getTableName()} ec ON ec.id = Event.EventCategory 
							WHERE ec.SiteID = %s {$pub} {$past} ORDER BY StartDate ASC ", $db->sanitizeInput(SITE_ID, 'int'));

        if ($limit != NULL) {
            $query = sprintf("%s LIMIT %s, %s", $query, $db->sanitizeInput($start, 'int'), $db->sanitizeInput($limit, 'int'));
        }

        $db->query($query, true);
        $events = array();

        for ($i = 0; $i < $db->getResultCount(); $i++) {
            array_push($events, new Event($db->getRow($i)));
        }

        return $events;
    }

    /**
     *
     * @param mixed $id the id or alias to use to find the event
     * @return Event an Event object
     */
    public function getEvent($id) {
        $db = $this->getDatabase();

        $query = sprintf("SELECT Event.* FROM {$this->Event->getTableName()} AS Event "
            . "INNER JOIN {$this->EventCategory->getTableName()} ec ON ec.id = Event.EventCategory "
            . "WHERE ec.SiteID = %s AND Event.id = %s OR FriendlyURL = %s AND Published = 'true' ", $db->sanitizeInput(SITE_ID, 'int'), $db->sanitizeInput($id, 'int'), $db->sanitizeInput($id, 'text'));

        $db->query($query, true);
        $event = new Event($db->getRow());

        return $event;
    }

    public function getFeedURL() {
        if (SEF_URLS) {
            return kan_fix_url("../" . SITE_TAG . "/feed/events/");
        }

        return kan_fix_url("../pages/feed.php?siteid=" . SITE_TAG . "&content=events");
    }

    public function render() {
		global $site;
		
        $event = NULL;
        $category = NULL;

        if (isset($_GET['category'])) {
            $category = $this->getEventCategory(kan_get_parameter('category'));
        }

        if (isset($_GET['id'])) {
            $event = $this->getEvent(kan_get_parameter('id'));
			$site->setData('SiteDescription', substr(strip_tags($event->getDescription()), 0, 200) );
            
        } else if (isset($_GET['url'])) {
            // the url parameters
            $parts = explode("/", kan_get_parameter('url'));

            // if the url parameters contains more than two parameters then the url is
            // valid and the article can be loaded. e.g. news/article-title
            if (count($parts) >= 1 && !empty($parts[0])) {
                $category = $this->getEventCategory(kan_clean_input($parts[0]));
            }

            if (count($parts) >= 2 && !empty($parts[1])) {
                $event = $this->getEvent(kan_clean_input($parts[1]));
				$site->setData('SiteDescription', substr(strip_tags($event->getDescription()), 0, 200) );
            }
        }
        
        $this->set('event',$event);
        $this->set('category', $category);

        // call parent render function
        parent::render();
    }

}

?>